package com.chii.colorization.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chii.colorization.R;
import com.chii.colorization.utils.connes.MyUrl;
import com.chii.colorization.utils.connes.OkHttpUtil;
import com.chii.colorization.utils.SHA1Util;
import com.chii.colorization.utils.SPUtil;
import com.chii.colorization.utils.TimeUtils;

import java.io.IOException;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.chii.colorization.utils.ActivityCodes.REQUESTCODE_FROM_REGISTER;


public class LoginActivity extends AppCompatActivity {
    public static String TAG = LoginActivity.class.getName();

    @BindView(R.id.login_imageView)
    ImageView login_imageView;
    @BindView(R.id.login_morning)
    TextView login_morning;
    @BindView(R.id.username)
    EditText usernameEditText;
    @BindView(R.id.password)
    EditText passwordEditText;
    @BindView(R.id.toregister)
    Button toregisterButton;
    @BindView(R.id.login)
    Button loginButton;
    @BindView(R.id.retrieve_password)
    TextView retrievePassword;
    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        initHandler();
        //初始化返回按键
        initAction();
        //更改主题
        changeStyles();
        //登录框
        initEdit();
    }

    private void initAction() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    private void initEdit() {
        String saveUsername = (String) SPUtil.get(LoginActivity.this, "username", "");
        String savePassword = (String) SPUtil.get(LoginActivity.this, "password", "");
        usernameEditText.setText(saveUsername);
        passwordEditText.setText(savePassword);
    }

    private void changeStyles() {
        if (new TimeUtils().getCurrentTime()) {
//            Toast.makeText(this, "晚上", Toast.LENGTH_SHORT).show();
            login_imageView.setImageResource(R.drawable.good_night_color);
            login_morning.setText("Night");
        } else {
//            Toast.makeText(this, "白天", Toast.LENGTH_SHORT).show();
            login_imageView.setImageResource(R.drawable.good_morning_color);
        }
    }


    @OnClick({R.id.login, R.id.toregister, R.id.retrieve_password})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login:
                //限制点击登录
                loginButton.setEnabled(false);
                String username = usernameEditText.getText().toString();
                String password = passwordEditText.getText().toString();
                String finalPassword = SHA1Util.getSHA(password);
                SPUtil.put(LoginActivity.this, "username", username);
                SPUtil.put(LoginActivity.this, "password", password);
                SPUtil.put(LoginActivity.this, "finalPassword", finalPassword);

                login();
                break;
            case R.id.toregister:
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivityForResult(intent, REQUESTCODE_FROM_REGISTER);
                break;
            case R.id.retrieve_password:
                Toast.makeText(this, "那就重新注册一个新账号吧！", Toast.LENGTH_SHORT).show();
            default:
        }
    }


    private void login() {
        //url访问以及密码加密
        String saveUsername = (String) SPUtil.get(LoginActivity.this, "username", "");
        String saveFinalPassword = (String) SPUtil.get(LoginActivity.this, "finalPassword", "");
        HashMap<String, String> map = new HashMap<>();
        map.put("username", saveUsername);
        map.put("password", saveFinalPassword);
        map.put("client_id", "color-client");
        map.put("client_secret", "FZfXZcltBeng");
        map.put("grant_type", "password");
        map.put("scope", "server");
        OkHttpUtil okHttpUtil = OkHttpUtil.getInstance(this);
        okHttpUtil.post(MyUrl.oauth, map, new OkHttpUtil.MyCallback() {
            @Override
            public void success(String s) {
                /*{
                    "access_token": "6739f3dd-9bae-4dee-9286-e420cddf3f17",
                    "token_type": "bearer",
                    "refresh_token": "ff1d1aa7-e78f-4e87-a84e-d3016cff2756",
                    "expires_in": 25199,
                    "scope": "server"
                }
                {
                    "error": "invalid_grant",
                    "error_description": "Bad credentials"
                }*/
                System.out.println(s);
                JSONObject jsonObject = (JSONObject) JSON.parse(s);
                if (jsonObject.containsKey("access_token")) {
                    Long time = System.currentTimeMillis()+jsonObject.getInteger("expires_in")*1000;
                    jsonObject.put("end_time", time);
                    Message message = new Message();
                    message.what = 2001;
                    message.obj = jsonObject;
                    mHandler.sendMessage(message);
                } else if (jsonObject.containsKey("code")) {
                    Message message = new Message();
                    message.what = jsonObject.getInteger("code");
                    message.obj = jsonObject.getString("msg");
                    mHandler.sendMessage(message);
                }
            }

            @Override
            public void failed(IOException e) {
                Message message = new Message();
                message.what = 0;
                mHandler.sendMessage(message);
            }
        });
    }


    private void getRole() {
        String saveUsername = (String) SPUtil.get(LoginActivity.this, "username", "");
        HashMap<String, String> map = new HashMap<>();
        map.put("username", saveUsername);
        OkHttpUtil okHttpUtil = OkHttpUtil.getInstance(this);
        okHttpUtil.get(MyUrl.role, map, new OkHttpUtil.MyCallback() {
            @Override
            public void success(String s) {
                System.out.println(s);
                JSONObject jsonObject = (JSONObject) JSON.parse(s);
                Boolean vip = false;
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                for (Object o : jsonArray) {
                    JSONObject object = (JSONObject) o;

                    if ("vip".equals(object.getString("roleName"))) {
                        vip = true;
                        break;
                    }
                }
                Message message = new Message();
                message.what = 2002;
                message.obj = vip;
                mHandler.sendMessage(message);

            }

            @Override
            public void failed(IOException e) {
                Message message = new Message();
                message.what = 0;
                mHandler.sendMessage(message);
            }
        });
    }
    private void initHandler() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case 2001:
                        SPUtil.put(LoginActivity.this, "token", msg.obj.toString());
                        getRole();
                        break;
                    case 2002:
                        SPUtil.put(LoginActivity.this, "vip", (Boolean)msg.obj);
                        Intent intent = new Intent();
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                        break;
                    case 401:
                        Toast.makeText(LoginActivity.this, "账号密码错误，请重试",
                                Toast.LENGTH_SHORT).show();
                        break;
                    default:
                }
                //可以重新点击登录
                loginButton.setEnabled(true);
                return false;
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 当otherActivity中返回数据的时候，会响应此方法
        // requestCode和resultCode必须与请求startActivityForResult()和返回setResult()的时候传入的值一致。
        Log.d(TAG, "onActivityResult: " + requestCode + "  " + resultCode);
        Log.d(TAG, "RESULT_OK " + Activity.RESULT_OK);
        switch (requestCode) {
            //注册回传
            case REQUESTCODE_FROM_REGISTER:
                if (resultCode == Activity.RESULT_OK) {
                    //停止登录和注册按键
                    loginButton.setEnabled(false);
                    toregisterButton.setEnabled(false);

                    Log.d(TAG, "RegisterActivity.REQUESTCODE_FROM_REGISTER ");
                    Boolean registered = data.getBooleanExtra("registered", false);
                    Toast.makeText(this, "注册成功,正在登录", Toast.LENGTH_SHORT).show();
                    if (registered) {
                        login();
                    }
                }
                break;
            default:
                break;
        }

    }

    //左上角返回处理
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

}
